"""
信号验证配置加载器
加载和管理 validation_rules.yaml 配置文件
"""
import os
import yaml
import logging

logger = logging.getLogger('ValidationConfigLoader')

# 配置文件路径
VALIDATION_RULES_FILE = os.path.join(
    os.path.dirname(__file__), 
    'config', 
    'validation_rules.yaml'
)


class ValidationConfigLoader:
    """信号验证配置加载器"""
    
    def __init__(self):
        self.config = {}
        self._load_config()
    
    def _load_config(self):
        """加载配置文件"""
        try:
            if not os.path.exists(VALIDATION_RULES_FILE):
                logger.warning(f"配置文件不存在: {VALIDATION_RULES_FILE}，使用默认配置")
                self.config = self._get_default_config()
                return
            
            with open(VALIDATION_RULES_FILE, 'r', encoding='utf-8') as f:
                self.config = yaml.safe_load(f)
            
            logger.info(f"✅ 信号验证配置加载成功: {VALIDATION_RULES_FILE}")
            
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}，使用默认配置")
            self.config = self._get_default_config()
    
    def _get_default_config(self):
        """获取默认配置（硬编码备用）"""
        return {
            'validation_rules': {
                'high': {
                    'required_validators': ['consecutive', 'volume', 'price'],
                    'min_confirmations': 3,
                    'min_confidence': 0.7
                },
                'medium': {
                    'required_validators': ['consecutive', 'volume'],
                    'min_confirmations': 2,
                    'min_confidence': 0.6
                },
                'low': {
                    'required_validators': ['consecutive'],
                    'min_confirmations': 1,
                    'min_confidence': 0.5
                },
                'normal': {
                    'required_validators': [],
                    'min_confirmations': 0,
                    'min_confidence': 0.0
                }
            },
            'validator_params': {
                'consecutive_time': {
                    'lookback_minutes': 3,
                    'threshold': 0.5
                },
                'volume_reliability': {
                    'min_volume_ratio': 0.2,
                    'volatility_threshold': 0.4
                },
                'price_trend': {
                    'min_break_pct': 0.005,
                    'lookback': 2
                }
            },
            'liquidity_thresholds': {
                'high_volume': 5000000,
                'medium_volume': 1000000,
                'lookback_days': 20
            },
            'time_sensitivity': {
                'high_period': 15,
                'medium_period': 30,
                'low_period': 60
            },
            'abnormal_detection': {
                'limit_threshold': 0.095,
                'volume_surge_ratio': 5.0,
                'volume_dry_ratio': 0.2,
                'price_volatility': 0.05
            },
            'logging': {
                'level': 'INFO',
                'save_filtered_signals': True,
                'print_statistics': True
            }
        }
    
    @property
    def validation_rules(self):
        """验证规则配置"""
        return self.config.get('validation_rules', {})
    
    @property
    def validator_params(self):
        """验证器参数配置"""
        return self.config.get('validator_params', {})
    
    @property
    def liquidity_thresholds(self):
        """流动性阈值配置"""
        return self.config.get('liquidity_thresholds', {})
    
    @property
    def time_sensitivity(self):
        """时间敏感度配置"""
        return self.config.get('time_sensitivity', {})
    
    @property
    def abnormal_detection(self):
        """异常市场检测配置"""
        return self.config.get('abnormal_detection', {})
    
    @property
    def logging_config(self):
        """日志配置"""
        return self.config.get('logging', {})
    
    def reload(self):
        """重新加载配置"""
        logger.info("重新加载信号验证配置...")
        self._load_config()


# ============================================
# 全局单例
# ============================================

_validation_config_loader = None


def get_validation_config_loader() -> ValidationConfigLoader:
    """获取信号验证配置加载器（单例）"""
    global _validation_config_loader
    if _validation_config_loader is None:
        _validation_config_loader = ValidationConfigLoader()
    return _validation_config_loader


# ============================================
# 导出配置对象（方便导入）
# ============================================

VALIDATION_RULES = get_validation_config_loader().validation_rules
VALIDATOR_PARAMS = get_validation_config_loader().validator_params
LIQUIDITY_THRESHOLDS = get_validation_config_loader().liquidity_thresholds
TIME_SENSITIVITY = get_validation_config_loader().time_sensitivity
ABNORMAL_DETECTION = get_validation_config_loader().abnormal_detection
VALIDATION_LOGGING = get_validation_config_loader().logging_config


def reload_validation_config():
    """
    重新加载信号验证配置（热更新）
    
    使用示例:
        from validation_config_loader import reload_validation_config
        reload_validation_config()
    """
    global VALIDATION_RULES, VALIDATOR_PARAMS, LIQUIDITY_THRESHOLDS
    global TIME_SENSITIVITY, ABNORMAL_DETECTION, VALIDATION_LOGGING
    
    _config_loader = get_validation_config_loader()
    _config_loader.reload()
    
    # 更新全局变量
    VALIDATION_RULES = _config_loader.validation_rules
    VALIDATOR_PARAMS = _config_loader.validator_params
    LIQUIDITY_THRESHOLDS = _config_loader.liquidity_thresholds
    TIME_SENSITIVITY = _config_loader.time_sensitivity
    ABNORMAL_DETECTION = _config_loader.abnormal_detection
    VALIDATION_LOGGING = _config_loader.logging_config
    
    logger.info("✅ 信号验证配置已重新加载")


if __name__ == '__main__':
    # 测试配置加载
    import logging
    logging.basicConfig(level=logging.INFO)
    
    loader = get_validation_config_loader()
    print("\n" + "="*50)
    print("📋 信号验证配置加载测试")
    print("="*50)
    print(f"\n验证规则: {VALIDATION_RULES}")
    print(f"\n验证器参数: {VALIDATOR_PARAMS}")
    print(f"\n流动性阈值: {LIQUIDITY_THRESHOLDS}")
    print(f"\n时间敏感度: {TIME_SENSITIVITY}")
    print(f"\n异常检测: {ABNORMAL_DETECTION}")
    print(f"\n日志配置: {VALIDATION_LOGGING}")
    print("\n" + "="*50)

